package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	// 通过标签，将外键定义为：UserRefer
	CreditCards []CreditCard `gorm:"foreignkey:UserRefer"`
}

type CreditCard struct {
	gorm.Model
	Number    string
	UserRefer uint // 新定义的外键名
}

func Mysqlinit()  (db *gorm.DB) {
	fmt.Print("My init DB")
	dsn := "root:root@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("err")
	}
	return db
}

func My_first_table(db *gorm.DB)  {
	fmt.Println("My_first_table   create table Product ")
	// Migrate the schema
	db.AutoMigrate(&User{})
	db.AutoMigrate(&CreditCard{})

}

func create_user(db *gorm.DB)  {
	fmt.Println("My_first_table   create table Product ")
	// Migrate the schema
	c := User{
		CreditCards: "2",
	}
	//插入一条用户数据
	//下面代码会自动生成SQL语句：INSERT INTO `users` (`username`,`password`,`createtime`) VALUES ('tizi365','123456','1540824823')
	if err := db.Create(&c).Error; err != nil {
		fmt.Println("插入失败", err)
		return
	}

}




func main() {
	//dsn := "user:pass@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := "root:root@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		fmt.Println("err")
	}
	if db != nil {
		fmt.Println("db")

	}
	Mydb := Mysqlinit()
	My_first_table(Mydb)

	create_user(Mydb)


	user := User{}
	// 查询用户数据
	//自动生成sql： SELECT * FROM `users`  WHERE (username = 'tizi365') LIMIT 1
	db.Where("username = ?", "tizi365").First(&user)
	fmt.Println(user)




}